﻿using HAF.Core.Datas;
using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using RDS.Core;
using RDSEngine.WorkItems;
using System;
using System.Web.Http;

namespace RDSEngine.Controllers
{
    //[RoutePrefix("api/gather")]
    public class GatherController : ApiController
    {
        //public IHttpActionResult Index()
        //{
        //    return Json(new ReturnJson() { Statu = 1, Comment = "金沙引擎：请求成功", ReturnValues = null });
        //}
        //private string _reqIP = "";
        private void ShowMessage(string msg)
        {
            LogHelper.WriteDebugLog(msg);
            RuntimeAdapter.ShowConsol(msg);
        }

        //[LogFilter]
        //[Route("POST")]
        [HttpPost]
        public IHttpActionResult Post([FromBody]object value)
        {
            string backMsg = string.Empty;
            //获取客户端IP地址
            string clientIP = RDSEngine.WorkItems.HttpRequestMessageExtensions.GetClientIpAddress(Request);

            #region 直接获取请求流中数据
            //Stream stream = Stream.Null;
            //HttpContent content = this.Request.Content;
            //Task readTask = content.ReadAsStreamAsync().ContinueWith((task) => { stream = task.Result; });
            //readTask.Wait();

            //string data = string.Empty;
            //using (StreamReader reader = new StreamReader(stream))
            //{
            //    data = reader.ReadToEnd();
            //}
            #endregion 直接获取请求流中数据

            ShowMessage(string.Format("金沙引擎：接收到来自{0}的资源采集请求", clientIP));

            if (value != null)
            {
                try
                {
                    //var reqParams = value as RequestTask;
                    RequestTask task = JsonAssistant.Deserialize<RequestTask>(value.ToString());
                    if (task == null)
                    {
                        ShowMessage("请求参数获取异常");
                        return Json(new RdsReturnJson() { Statu = -1, Comment = "请求参数获取异常！", ReturnValues = null });
                    }
                    else
                    {
                        if (RuntimeAdapter.RunPugins != null && RuntimeAdapter.RunPugins.Plugins != null)
                        {
                            WorkPlugin runItem = RuntimeAdapter.RunPugins.Plugins.Find(t => t.Tag.ToLower() == task.Type.ToLower());
                            if (runItem != null)
                            {
                                LoadWorker.GetInstance().LoadAssembly(runItem.LoadPluginFile);
                                LoadWorker.GetInstance().Invoke(runItem.LoadClass, "Regist", task.ID, task.Task);
                                ShowMessage("添加下载任务到执行队列完成");
                            }
                        }

                    }
                    ShowMessage(string.Format("同步回馈{0}请求", clientIP));
                    return Json(new RdsReturnJson() { Statu = 1, Comment = "成功", ReturnValues = null });
                }
                catch (Exception ex)
                {
                    ShowMessage(string.Format("请求异常:{0}", ex.ToString()));
                    return Json(new RdsReturnJson() { Statu = -1, Comment = "请求参数获取异常！", ReturnValues = null });
                }
                
            }
            else
            {
                backMsg = string.Format("金沙引擎：来自{0}的资源采集请求处理失败，请求参数为空", clientIP);
                ShowMessage(backMsg);
                return Json(new RdsReturnJson() { Statu = -1, Comment = backMsg, ReturnValues = null });
            }
        }
    }
}
